﻿Public Class GlyphCanvasScrollViewer
    Inherits ScrollViewer

    Shared Sub New()
        HorizontalScrollBarVisibilityProperty.OverrideMetadata(GetType(GlyphCanvasScrollViewer), New FrameworkPropertyMetadata(ScrollBarVisibility.Visible))
    End Sub

    Public Sub New()
    End Sub



    Private Function CalculateNewScrollOffset(oldOffset As Double, oldExtentLength As Double, oldViewportLength As Double, newExtentLength As Double, newViewportLength As Double) As Double
        If oldExtentLength = 0 Then
            Return newExtentLength / 2 - newViewportLength / 2
        Else
            Return (oldOffset + oldViewportLength / 2) / oldExtentLength * newExtentLength - newViewportLength / 2
        End If
    End Function

    Protected Overrides Sub OnScrollChanged(e As ScrollChangedEventArgs)
        MyBase.OnScrollChanged(e)
        If e.ExtentHeightChange <> 0 OrElse e.ViewportHeightChange <> 0 Then
            ScrollToVerticalOffset(CalculateNewScrollOffset( _
                e.VerticalOffset, e.ExtentHeight - e.ExtentHeightChange, e.ViewportHeight - e.ViewportHeightChange, e.ExtentHeight, e.ViewportHeight))
        End If
        If e.ExtentWidthChange <> 0 OrElse e.ViewportWidthChange <> 0 Then
            ScrollToHorizontalOffset(CalculateNewScrollOffset( _
                e.HorizontalOffset, e.ExtentWidth - e.ExtentWidthChange, e.ViewportWidth - e.ViewportWidthChange, e.ExtentWidth, e.ViewportWidth))
        End If
    End Sub

End Class
